var tableIns;
var form;
var tree;
var ctxPath = '/';
$(function () {
    layui.config({
        base: '/' + 'lib/layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index'//主入口模块
    }).use(['index', 'table', 'form', 'tree'], function () {
        var table = layui.table;
        form = layui.form;
        tree = layui.tree;
        // 渲染表格
        tableIns = table.render({
            elem: '#table',
            toolbar: '#table-title',
            url: 'rolePager',
            page: true,
            cols: [[
                {type: 'numbers'},
                {field: 'name', title: '角色名', align: 'center'},
                {field: 'seq', title: '排序', width: 100, align: 'center'},
                {field: 'description', title: '角色描述', align: 'center'},
                {field: 'status', title: '是否启用', align: 'center', templet: '#islock'},
                {field: 'right', title: '操作', toolbar: '#table-toolbar', align: 'center'},
            ]],
            request: {
                pageName: 'page' //页码的参数名称，默认：page
                , limitName: 'limit' //每页数据量的参数名，默认：limit
            }
        });

        //监听行工具事件
        table.on('tool(table)', function (obj) {
            var data = obj.data;
            if (obj.event === 'del') {
                openDel(obj)
            } else if (obj.event === 'edit') {
                openEdit(data)
            } else if (obj.event === 'grant') {
                openGrant(data);
            }
        });
        //监听是否启用状态操作
        form.on('switch(islock)', function (obj) {
            setRoleStatus(obj, this.value, this.name, obj.elem.checked);
        });
        form.on('submit(submitUser)', function (data) {
            roleSubmit($("#oper").val())
        })
    });
})

function buildResourceTree(type) {
    console.log('type值'+type)
    $.ajax({
        type: "GET",
        url: ctxPath + "config/resource/treeInfo?type=" +  type,
        async : false,
        success: function (result) {
            if (result.code == "1") {
                var data = result.obj
                tree.render({
                    elem: '#resourceTree'  //绑定元素
                    , showCheckbox: true
                    , data: data
                    , id: 'treeId'
                });
            } else {
                layer.alert(result.msg)
            }
        }
    });
}
function submitCancel() {
    layer.closeAll()

}
/**
 * 删除角色
 * @param obj
 */
function openDel(obj) {
    var data = obj.data
    layer.confirm('您确定要删除' + data.name + '角色么', function () {
        $.ajax({
            type: "DELETE",
            data: {
                "id": data.id
            },
            url: ctxPath + "system/role/roleInfo",
            complete: function () {
                tableReload();
            }
        });
    });
}

function openAdd() {
    layer.open({
            type: 1,
            title: "角色管理",
            fixed: false,
            resize: false,
            shadeClose: true,
            area: ['30%', '50%'],
            content: $('#roleEdit'),
        success: function () {
            $("#oper").val("0")
        },
            end: function () {
                cleanForm("roleForm");
                tableReload();
            }
        })
}

/**
 * @param data layui中保存的table中的对应的此条信息
 */
function openEdit(data) {
    layer.open({
        type: 1,
        title: "角色管理",
        fixed: false,
        resize: false,
        shadeClose: true,
        area: ['30%', '50%'],
        content: $('#roleEdit'),
        success: function () {
            //填充表单
            form.val('roleForm', data);
            renderForm()
            $("#oper").val("1")
        }, end: function () {
            cleanForm("roleForm")
            tableReload();
        }
    });
}

function tableReload() {
    tableIns.reload({
        page: {
            curr: 1 //重新从第 1 页开始
        }
    });
}

/**
 * 提交role表单信息
 */
function roleSubmit(oper) {
    var type = oper == "0" ? "POST" : "PUT";
    console.log()
    $.ajax({
        type: type,
        data: $("#roleForm").serialize(),
        url: ctxPath + "system/role/roleInfo"
    });
}

//设置角色状态
function setRoleStatus(obj, id, name, checked) {
    var status = checked ? 1 : 0;
    var ParaIsLock = checked ? "启用" : "停用";
    //用户状态
    layer.confirm('您确定要把角色：' + name + '设置为' + ParaIsLock + '状态吗？', {
        btn: ['确认', '返回'] //按钮
        //点击关闭按钮事件
        , cancel: function () {
            tableReload()
        }
    }, function () {
        $.ajax({
            type: "PUT",
            data: {"id": id, "status": status},
            url: ctxPath + "system/role/status",
            complete: function () {
                tableReload()
            }
        });
    }, function () {
        tableReload()
    });
}

/**
 * 打开授权弹出层
 * @param data 角色信息
 */
function openGrant(data) {
    //初始化资源树
    buildResourceTree(data.type);
    layer.open({
        type: 1,
        title: "角色授权",
        fixed: false,
        resize: false,
        shadeClose: true,
        area: ['40%', '60%'],
        content: $('#roleGrant'),
        btn: ['确定', '取消'],
        success: function () {
            checkResource(data.id) //选中
        }, btn1: function () {
            grantSubmit(data.id);
            layer.closeAll();
        }, end: function () {
            tree.reload('treeId', {}); //重新加载树形控件
        }
    });
}

/**
 * 根据角色选中对应资源Tree节点
 * @param id
 */
function checkResource(id) {
    $.ajax({
        type: "GET",
        data: {
            "roleId": id
        },
        url: ctxPath + "system/roleResource/resourceIdList",
        success: function (result) {
            if (result.code == "1") {
                var data = result.obj;
                tree.setChecked('treeId', data); //设置选中
            } else {
                layer.alert(result.msg)
            }
        }
    });
}

/**
 * 提交授权信息
 * @param id 角色ID
 */
function grantSubmit(id) {
    tree = layui.tree;
    var checkData = tree.getChecked('treeId');
    var arr = getCheckedId(checkData);
    $.ajax({
        type: "POST",
        data: {
            "resourceId": arr,
            "roleId": id
        },
        url: ctxPath + "system/roleResource/resourceIdList",
        complete:function () {
            tableReload(); //刷新表格
        }
    });
}

/**
 * 递归获取所有选中的ID
 * @param jsonObj
 * @returns {string}
 */
function getCheckedId(jsonObj) {
    var id = "";
    $.each(jsonObj, function (index, item) {
        if (id !== "") {
            id = id + "," + item.id;
        } else {
            id = item.id;
        }
        var i = getCheckedId(item.children);
        if (i !== "") {
            id = id + "," + i;
        }
    });
    return id;
}
